'use strict'

import React, { Component } from 'react'
import Page from '../../../base/Page'
import Divider from '../../../ui/list/Divider'
import TextCard from '../../../ui/list/TextCard'
import TextLine from '../../../ui/list/TextLine'
import TextMultiLine from '../../../ui/list/TextMultiLine'
import ActionButton from '../../../ui/button/ActionButton'
import * as layout from '../../../configs/layout'
import * as color from '../../../configs/color'
import * as enums from '../enums'
import actions from '../actions'
import * as helper from '../../../utilities/helper'
import { formatDate, fixMoney } from '../../../utilities/helper'
import store from '../store'
import Loading from '../../../ui/dialog/Loading'
import findIndex from 'lodash/findIndex'

const footerStyle = {
    width: '100%',
    paddingLeft: layout.HORIZONTAL_PADDING,
    paddingRight: layout.HORIZONTAL_PADDING,
    backgroundColor: color.WHITE,
    position: 'fixed',
    bottom: 0
}

const actionButtonStyle = {
    float: 'right',
    marginLeft: '10px'
}

const actionsContainerStyle = {
    overflowX: 'hidden',
    padding: '8px 0 8px'
}

class Task extends Page {
    constructor(props) {
        super(props)

        this.handleRejectBtnClick = this.handleRejectBtnClick.bind(this)
        this.handleAcceptBtnClick = this.handleAcceptBtnClick.bind(this)
        this.handleFinishBtnClick = this.handleFinishBtnClick.bind(this)
        this.handleReScheduleBtnClick = this.handleReScheduleBtnClick.bind(this)
        this.handlerCancelAccept = this.handlerCancelAccept.bind(this)
        this.handleClickContact = this.handleClickContact.bind(this)
        this._onChange = this._onChange.bind(this)

        this.state = {
            task: store.getItem(this.props.params.id)
        }
    }

    _onChange() {

        const task = store.getItem(this.props.params.id)

        if (task) {
            this.setState({
                task: task
            })
        } else {
            this.props.router.replace('/board/new')
        }

    }

    componentDidMount() {
        store.addInitListener(this._onChange)
        store.addChangeListener(this._onChange)
    }

    componentWillUnmount() {
        store.removeInitListener(this._onChange)
        store.removeChangeListener(this._onChange)
    }

    componentDidUpdate(prevProps) {
        const prevId = prevProps.params.id
        const newId = this.props.params.id
        if (newId != prevId) {
            this.setState({
                task: store.getItem(newId)
            })
        }
    }

    handleRejectBtnClick() {
        this.props.router.push('/task/reject/' + this.props.params.id)
    }

    //接单
    handleAcceptBtnClick() {
        this.confirm({
            message: '是否确认接单操作',
            ok: () => {
                actions.accept(this.props.params.id, () => {
                    this.logger.collect({
                        cid: 'task',
                        aid: 'accept',
                        label: 'task_id',
                        value: this.props.params.id
                    })
                    this.props.router.goBack();
                })
            }
        })
    }

    //完成
    handleFinishBtnClick() {
        if (this.state.task.main_category == enums.TASK_CATEGORY.REPAIR) {
            this.props.router.push('/cashier/order/' + this.props.params.id)
        } else {
            this.confirm({
                message: '请确认已经获得用户认可再操作完成',
                ok: () => {
                    actions.complete(this.props.params.id, () => {
                        this.logger.collect({
                            cid: 'task',
                            aid: 'finish',
                            label: 'task_id',
                            value: this.props.params.id
                        })
                        this.props.router.goBack();
                    })
                }
            })
        }
    }

    //申请取消
    handlerCancelAccept() {
        this.props.router.push('/task/cancel/' + this.props.params.id)
    }

    // 调整时间
    handleReScheduleBtnClick() {
        this.props.router.push('/task/reschedule/' + this.props.params.id)
    }

    handleClickContact() {
        if (this.state.task.arrange_status == enums.TASK_STATUS.NEW) {
            return
        }
        location.href = 'tel:' + this.state.task.contact_phone
    }

    render() {

        const task = this.state.task
        const taskStatus = enums.TASK_STATUS

        const taskDetailsStyle = {
            marginBottom: task ? (task.arrange_status == taskStatus.DONE ? '0' : '60px') : '0'
        }

        const balance = task ? store.calcBalance(this.props.params.id) : null

        let actionsJSX = null
        let taskJSX = null

        if (task) {
            switch (task.arrange_status) {
                case taskStatus.NEW:
                    actionsJSX = (
                        <div style={actionsContainerStyle}>
                            <ActionButton onClick={this.handleAcceptBtnClick} style={actionButtonStyle} text="确认接单"
                                          themes="primary"/>
                            <ActionButton onClick={this.handleRejectBtnClick} style={actionButtonStyle} text="拒绝接单"
                                          themes="outline danger"/>
                        </div>
                    )
                    break
                case taskStatus.TOGO:
                    actionsJSX = (
                        <div style={actionsContainerStyle}>
                            <ActionButton onClick={this.handleFinishBtnClick} style={actionButtonStyle} text="完成"
                                          themes="primary"/>
                            <ActionButton onClick={this.handlerCancelAccept} style={actionButtonStyle} text="申请取消"
                                          themes="outline"/>
                            {task.main_category == enums.TASK_CATEGORY.REPAIR ?
                                <ActionButton onClick={this.handleReScheduleBtnClick} style={actionButtonStyle} text="调整时间"
                                              themes="outline"/>
                                : null}
                        </div>
                    )
                    break
                case taskStatus.DONE:
                    actionsJSX = null
                    break
            }

            switch (task.main_category) {
                case enums.TASK_CATEGORY.AYI:
                    taskJSX = (
                        <section style={taskDetailsStyle}>
                            <Divider title="阿姨任务"/>
                            <TextCard>
                                {task.arrange_status == enums.TASK_STATUS.NEW
                                    ?
                                    <TextLine label="分派时间" content={formatDate(task.op_time * 1000, 'MM-dd hh:mm')}/>
                                    :
                                    <TextLine label="接单时间" content={task.accept_time != 0 ? formatDate(task.accept_time*1000, 'MM-dd hh:mm') : '未知'}/>
                                }
                                <TextLine label="任务类型" content={enums.ARRANGE_OPERATION_NAME[task.arrange_operate]}/>
                                <TextLine label="任务日期" content={task.work_time.start_date + '到' + task.work_time.end_date}/>
                                <TextLine label="任期时间" content={task.work_time.start_hours + ' - ' + task.work_time.end_hours}/>
                            </TextCard>
                            <Divider title="订单内容"/>
                            <TextCard>
                                <TextLine label="订单编号" content={task.order_number}/>
                                <TextLine contentStyle={task.arrange_status != enums.TASK_STATUS.NEW ? {color: color.INVERSE} : null} onClick={this.handleClickContact} label="联系人" content={
                            task.contact_person
                            + ' '
                            + (task.arrange_status == enums.TASK_STATUS.NEW ? helper.maskPhoneNumber(task.contact_phone) : task.contact_phone)}/>
                                <TextLine label="服务地址" content={task.contact_address}/>
                                <TextLine label="服务内容" content={enums.ORDER_TYPE_NAME[task.order_type]}/>
                                {task.order_type == enums.ORDER_TYPE.SINGLE_HOURLY_EMPLOYEE
                                    ?
                                    <TextLine label="增值服务" content={
                                    task.order_tags.length > 0
                                    ? '自带' + task.order_tags.map(id => enums.AYI_SERVICE_TAGS[id].SHORT_NAME).join('，')
                                    : '无'
                                    }/>
                                    :
                                    null
                                }
                                <TextLine label="服务周期" content={task.service_cycle ? '每周' + helper.parseWeekdays(task.service_cycle) : '无'}/>
                                <TextLine label="服务时长" content={task.service_time}/>
                                {task.order_type == enums.ORDER_TYPE.YUESAO
                                    ?
                                    <TextLine label="预产期" content={task.edc_time}/>
                                    :
                                    <TextLine label="服务时间" contentStyle={{fontSize: '12px'}} content={task.service_start_time + ' - ' + task.service_end_time}/>
                                }
                                <TextLine label="特殊要求" content={task.order_note}/>
                                <TextMultiLine label="注意事项" content={task.arrange_note}/>
                                <TextLine label="订单金额" content={'￥' + fixMoney(balance.total)}/>
                                <TextLine label="返点金额" content={'￥' + fixMoney(balance.rebate)}/>
                                <TextLine label="实际工资" content={'￥' + fixMoney(balance.income)}/>
                            </TextCard>
                        </section>
                    )
                    break
                case enums.TASK_CATEGORY.REPAIR:
                    taskJSX = (
                        <section style={taskDetailsStyle}>
                            <Divider title="维修任务"/>
                            <TextCard>
                                <TextLine label="分派时间" content={formatDate(task.op_time * 1000, 'MM-dd hh:mm')}/>
                                <TextLine contentStyle={task.arrange_status != enums.TASK_STATUS.NEW ? {color: color.INVERSE} : null} onClick={this.handleClickContact} label="联系人" content={
                            task.contact_person
                            + ' '
                            + (task.arrange_status == enums.TASK_STATUS.NEW ? helper.maskPhoneNumber(task.contact_phone) : task.contact_phone)}/>
                                <TextLine label="服务地址" content={task.contact_address}/>
                                <TextLine label="服务类别" content={enums.ORDER_TYPE_NAME[task.order_type]}/>
                                <TextLine label="服务时间" content={formatDate(task.work_time.start_date, 'M月d日') + ' ' + task.work_time.start_hours + ' - ' + task.work_time.end_hours}/>
                            </TextCard>
                            <Divider title="订单内容"/>
                            <TextCard>
                                <TextLine label="订单编号" content={task.order_number}/>
                                <TextLine label="联系人" content={
                            task.contact_person
                            + ' '
                            + (task.arrange_status == enums.TASK_STATUS.NEW ? helper.maskPhoneNumber(task.contact_phone) : task.contact_phone)}/>
                                <TextLine label="服务地址" content={task.contact_address}/>
                                <TextLine label="服务类别" content={enums.ORDER_TYPE_NAME[task.order_type]}/>
                                <TextLine label="故障描述" content={task.describe}/>
                                <TextLine label="服务时间" content={formatDate(task.work_time.start_date, 'M月d日') + ' ' + task.work_time.start_hours + ' - ' + task.work_time.end_hours}/>
                                <TextLine label="用户备注" content={task.order_note}/>
                                <TextMultiLine label="注意事项" content={task.arrange_note}/>
                                <TextLine label="订单金额" content={task.arrange_status == enums.TASK_STATUS.DONE ? '￥' + fixMoney(balance.total) : '待定'}/>
                                <TextLine label="返点金额" content={task.arrange_status == enums.TASK_STATUS.DONE ? '￥' + fixMoney(balance.rebate) : '待定'}/>
                                <TextLine label="实际工资" content={task.arrange_status == enums.TASK_STATUS.DONE ? '￥' + fixMoney(balance.income) : '待定'}/>
                            </TextCard>
                        </section>
                    )
                    break
            }

        }

        return task ?
            <div>
                {taskJSX}
                {actionsJSX ? <footer style={footerStyle}>{actionsJSX}</footer> : null}
            </div>
            :
            <Loading on={true}/>
    }
}

Task.defaultProps = {
    title: '订单详情'
}

export default Task